/*	UseComsat class definition.
 *
*/

#include "UseComsat.h"
#include "Blackboard.h"

void UseComsat::Enter()
{
	DEBUG_PRINT("UseComsat(%p) entering.\n", this);
}

void UseComsat::Execute()
{
	tower->useTech(BWAPI::TechTypes::Scanner_Sweep,target);	
	control->FinishWithSuccess();
}

void UseComsat::Exit()
{
	lastUsed = BWAPI::Broodwar->getFrameCount();
	DEBUG_PRINT("Exiting UseComsat behavior.\n");
}

bool UseComsat::CheckConditions()
{
	DEBUG_PRINT("Checking UseComsat conditions.\n");
	if(BWAPI::Broodwar->getFrameCount()-lastUsed > frameInterval)
	{
		std::list<BWAPI::Unit*>* towers = BB->GetUnitsByTypeGeneral(BWAPI::UnitTypes::Terran_Comsat_Station);
		bool foundTower = false;
		if(towers)
		{
			for(std::list<BWAPI::Unit*>::iterator tow = towers->begin(); tow != towers->end(); tow++)
			{
				if((*tow)->isCompleted() && (*tow)->getEnergy() >= 50)
				{
					tower = *tow;
					foundTower = true;
					break;
				}
			}
			if(foundTower)
			{
				std::set<BWAPI::Unit*> enemyUnits  = BWAPI::Broodwar->enemy()->getUnits();
				for(std::set<BWAPI::Unit*>::iterator it = enemyUnits.begin(); it != enemyUnits.end(); it++)
				{
					if((*it)->isAttacking() && !(*it)->isDetected())
					{
						target = (*it)->getPosition();
						return true;
					}
				}
				if(BB->GetCloakedEnemyPosition(&target))
					return true;
			}
		}
	}
	return false;
}